package org.devf.fork.imsimulator.play;

import cn.hutool.core.io.IoUtil;

import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 异步播放线程
 */
public class PlayThread implements Runnable {

    private File file;

    public PlayThread(File file) {
        this.file = file;
    }

    @Override
    public void run() {
        SourceDataLine sourceDataLine = null;
        BufferedInputStream bufIn = null;
        AudioInputStream audioIn = null;
        try {
            bufIn = new BufferedInputStream(new FileInputStream(file));
            audioIn = AudioSystem.getAudioInputStream(bufIn); // 可直接传入file

            AudioFormat format = audioIn.getFormat();
            sourceDataLine = AudioSystem.getSourceDataLine(format);
            sourceDataLine.open();

            FloatControl control = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
            control.setValue(control.getMaximum());

            sourceDataLine.start();

            byte[] buf = new byte[512];
            int len = -1;
            while ((len = audioIn.read(buf)) != -1) {
                sourceDataLine.write(buf, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sourceDataLine != null) {
                sourceDataLine.drain();
                sourceDataLine.close();
            }
            IoUtil.close(bufIn);
            IoUtil.close(audioIn);
        }
    }
}